package cn.starlightsoftware.sherly.service.user;

import cn.hutool.core.bean.BeanUtil;
import cn.starlightsoftware.sherly.controller.admin.user.vo.UserPageReqVO;
import cn.starlightsoftware.sherly.controller.admin.user.vo.UserRoleUpdateReqVO;
import cn.starlightsoftware.sherly.controller.admin.user.vo.UserSaveReqVO;
import cn.starlightsoftware.sherly.db.mysql.permission.UserRoleMapper;
import cn.starlightsoftware.sherly.db.mysql.user.UserMapper;
import cn.starlightsoftware.sherly.model.PageResult;
import cn.starlightsoftware.sherly.db.model.permission.UserRoleDO;
import cn.starlightsoftware.sherly.db.model.user.UserDO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 谷子毅
 * @date 2024/4/25
 */
@Service
public class UserServiceImpl implements UserService {

    @Value("${sherly.auth.default-password}")
    private String defaultPassword;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public PageResult<UserDO> page(UserPageReqVO reqVO) {
        return userMapper.selectPage(reqVO);
    }

    @Override
    public void save(UserSaveReqVO reqVO) {
        UserDO user = BeanUtil.copyProperties(reqVO, UserDO.class);
        user.setPassword(passwordEncoder.encode(defaultPassword));
        userMapper.insert(user);
    }

    @Override
    public UserDO detail(String userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public void delete(String userId) {
        userMapper.deleteById(userId);
    }

    @Override
    public void update(UserSaveReqVO reqVO) {
        userMapper.updateById(BeanUtil.copyProperties(reqVO, UserDO.class));
    }

    @Override
    public List<UserRoleDO> userRoleList(String userId) {
        return userRoleMapper.selectList(UserRoleDO::getUserId, userId);
    }

    @Override
    public void userRoleUpdate(UserRoleUpdateReqVO reqVO) {
        userRoleMapper.delete(UserRoleDO::getUserId, reqVO.getUserId());
        List<UserRoleDO> list = reqVO.getRoleIds()
                .stream()
                .map(roleId -> new UserRoleDO().setUserId(reqVO.getUserId()).setRoleId(roleId))
                .collect(Collectors.toList());

        userRoleMapper.insertBatch(list);
    }
}
